package com.mission.schedule.CommonDialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.support.annotation.StyleRes
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import com.android.volley.AuthFailureError
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException

import com.mission.schedule.R
import com.mission.schedule.applcation.App
import com.mission.schedule.bean.NewShareBean
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.constants.URLConstants
import com.mission.schedule.entity.ScheduleTable
import com.mission.schedule.utils.DateUtil
import com.mission.schedule.utils.ProgressUtil
import com.mission.schedule.utils.SharedPrefUtil
import org.json.JSONArray
import org.json.JSONObject
import java.util.HashMap

/**
 * 日程任务对话框
 * Created by liwei on 2017/4/18.
 */
@Suppress("DEPRECATION")
/**
 *
 * @param context
 * @param themeResId
 * @param windowManager
 * @param type 0 结束 1 删除
 */

class SixNewTaskDialog(context: Context, themeResId: Int,
                       windowManager: WindowManager, type: Int, titleId: String, userId: String)
    : Dialog(context, themeResId) {


    lateinit var callBack: CallBack

    internal var sharedPrefUtil: SharedPrefUtil = SharedPrefUtil(context, ShareFile.USERFILE)

    internal var view: View
    internal var type = type //0 结束 1 删除 2 开启任务
    var UserId = userId
    var titleId = titleId
    var windowManager = windowManager
    var map = mapOf<String, String>()


    init {
        setCanceledOnTouchOutside(true)

        view = LayoutInflater.from(context).inflate(R.layout.dialog_alterdelete, null)
        setContentView(view)

        val textView = view.findViewById(R.id.delete_tv) as TextView

        when (type) {
            0 -> textView.text = "确定要结束此任务吗?"
            1 -> textView.text = "确定要删除此任务吗?"
            2 -> textView.text = "确定要开启此任务吗?"
            3 -> {
                UserId = sharedPrefUtil.getString(ShareFile.USERID,"")
                textView.text = "确定要删除此连接吗？"
            }
        }

        view.findViewById<TextView>(R.id.delete_ok).setOnClickListener {
            if (type == 3) {
                updateLJ()
            } else {
                updateFrendTaskIsDown()
            }
            callBack.NewTaskDialogSure()
            dismiss()
        }
        view.findViewById<TextView>(R.id.delete_canel).setOnClickListener {
            callBack.NewTaskDialogCancel()
            dismiss()
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val window = window
        val params = window!!.attributes
        window.setGravity(Gravity.CENTER_HORIZONTAL)
        params.width = windowManager.defaultDisplay.width
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
        window.attributes = params
    }

    interface CallBack {
        fun NewTaskDialogSure()
        fun NewTaskDialogCancel()
    }

    open fun updateLJ() {
        map = App.getDBcApplication().querayOneCalenderDataTitleId(titleId)
        var data = JSONObject()
        var timetable = JSONArray()
        var json = JSONObject()
        json.put("updateState", 4)
        json.put("uid", UserId)
        json.put("puid", map[ScheduleTable.schcRecommendId])
        json.put("pname", map[ScheduleTable.schcRecommendName])
        json.put("ptitleimg", map[ScheduleTable.schImagePath])
        json.put("titleId", map[ScheduleTable.schSourceDesc])
        json.put("cdate", map[ScheduleTable.schDate])
        json.put("ctime", map[ScheduleTable.schTime])
        json.put("content", map[ScheduleTable.schContent])
        json.put("cisEnd", map[ScheduleTable.schIsEnd])
        json.put("cdisplayAlarm", map[ScheduleTable.schDisplayTime])
        json.put("cisAlarm", map[ScheduleTable.schIsAlarm])
        json.put("cbefortime", map[ScheduleTable.schBeforeTime])
        json.put("calarmsound", map[ScheduleTable.schRingCode])
        json.put("calarmsoundDesc", map[ScheduleTable.schRingDesc])
        json.put("cpostpone", map[ScheduleTable.schIsPostpone])
        json.put("cimportant", map[ScheduleTable.schIsImportant])
        json.put("cscore", "0")
        json.put("changeTime", DateUtil.nowTime())
        json.put("createTime", DateUtil.nowTime())
        json.put("remark", "")
        json.put("remark1", "0")
        json.put("remark2", "")
        json.put("remark3", "")
        json.put("remark4", "")
        json.put("remark5", "")
        timetable.put(json)

        data.put("timetable", timetable)

        loadData(data.toString())
    }

    private fun loadData(json: String) {
        val request3 = object : StringRequest(Method.POST, URLConstants.同步临时表数据, Response.Listener { s ->
            if (!TextUtils.isEmpty(s)) {
                try {
                    val goon = Gson()
                    val bean = goon.fromJson(s, NewShareBean::class.java)
                    if (bean.status == 0) {
                    }
                } catch (e: JsonSyntaxException) {
                    e.printStackTrace()
                }
            }
        }, Response.ErrorListener {
        }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map.put("data", json)
                return map
            }
        }
        request3.tag = "同步临时表数据"
        request3.retryPolicy = DefaultRetryPolicy(5000, 1, 1.0f)
        App.getHttpQueues().add(request3)
    }

    private fun updateFrendTaskIsDown() {

        var url = ""

        when (type) {
            0, 2 -> url = URLConstants.接收方任务结束
            1 -> url = URLConstants.接收方任务删除
        }

        val request = object : StringRequest(Method.POST, url, Response.Listener
        { _ ->
        }, Response.ErrorListener
        {

        }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map.put("uid", UserId)
                map.put("titleId", titleId)
                if (type != 3) {
                    if (type == 2) map.put("type", "0") else if (type == 0) map.put("type", "1")
                }
                return map
            }
        }
        request.tag = "updateFrendTaskIsDown"
        request.retryPolicy = DefaultRetryPolicy(3000, 1, 1.0f)
        App.getHttpQueues().add(request)
    }

}
